package cn.hnucm.searchesservice.dao.impl;

import cn.hnucm.searchesservice.dao.Dao;
import cn.hnucm.searchesservice.dao.TbGoodsImageDao;
import cn.hnucm.searchesservice.entity.TbGoodsImage;
import cn.hnucm.searchesservice.utils.MyInterId;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.index.reindex.UpdateByQueryRequest;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @author: chenjintao
 * @Date: 2021/12/20 23:21
 */
@Controller
public class TbGoodsImageDaoImpl implements TbGoodsImageDao {
    @Autowired
    @Qualifier("getRestHighLevelClient")
    private RestHighLevelClient client;


    /**
     * 获取一个商品号的所有图片路径
     *
     * @param goodsId
     * @return
     */
    @Override
    public List<TbGoodsImage> getImageByGoodsId(Integer goodsId) {

        SearchRequest request = new SearchRequest("tb_goods_image");
        SearchSourceBuilder builder = new SearchSourceBuilder()
                .query(QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("goodsId", String.valueOf(goodsId))));
        request.source(builder);
        try {
            ArrayList<TbGoodsImage> goodsImages = new ArrayList<>();
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits()) {
                TbGoodsImage goodsImage = new TbGoodsImage();
                goodsImage.setGoodsId((Integer) hit.getSourceAsMap().get("goodsId"));
                goodsImage.setImagePath((String) hit.getSourceAsMap().get("imagePath"));
                goodsImages.add(goodsImage);
            }
            return goodsImages;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 删除一条记录
     * @param tbGoodsImage
     * @return
     */
    @Override
    public Boolean deleteGoodsImage(TbGoodsImage tbGoodsImage) {
        DeleteByQueryRequest request = new DeleteByQueryRequest("tb_goods_image");
        //设置版本保护
        request.setConflicts("proceed");
        request.setQuery(QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("goodsId",tbGoodsImage.getGoodsId()))
                .must(QueryBuilders.matchQuery("imagePath",tbGoodsImage.getImagePath())));
        try {
            BulkByScrollResponse response =
                    client.deleteByQuery(request, RequestOptions.DEFAULT);
            return response.getDeleted() > 0;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加一条图片记录
     * @param tbGoodsImage
     * @return
     */
    @Override
    public Boolean addGoodsImage(TbGoodsImage tbGoodsImage) {
        IndexRequest request = new IndexRequest("tb_goods_image","_doc",String.valueOf(MyInterId.getIntegerId()));
        return Dao.getaCreateResult(request, JSON.toJSONString(tbGoodsImage), client);
    }

    /**
     * 修改一条图片记录
     * @param goodsId
     * @param oldImagePath
     * @param newImagePath
     * @return
     */
    @Override
    public Boolean updateGoodsImage(Integer goodsId, String oldImagePath, String newImagePath) {
        UpdateByQueryRequest request = new UpdateByQueryRequest("tb_goods_image");

        request.setQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("goodsId",goodsId))
                        .must(QueryBuilders.matchQuery("imagePath",oldImagePath)))
                .setScript(new Script("ctx._source['imagePath']='"+newImagePath+"';"));

        try {
            BulkByScrollResponse response = client.updateByQuery(request, RequestOptions.DEFAULT);
            return response.getUpdated()>0;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}
